package self.example.explore.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RestController;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author 1.
 * @version 1.0
 * @description: WebSocket 连接应用
 * @date 2023/4/12 22:34
 */
@Slf4j
@RestController
@ServerEndpoint("/inform")
public class InformServer {
    // 连接会话 session
    private Session session;
    // 客户端的id
    private String sid;
    // 是否建立连接
    private final AtomicBoolean connected = new AtomicBoolean(false);

    // 连接通道打开
    @OnOpen
    public void onOpen(Session session, @PathParam("sid") String id) {
        log.info("当前连接 id 为 {}", id);
        if(session == null) return;
        this.session = session;
        this.sid = id;
        //是否成功连接
        if(!connected.compareAndSet(false, true)){
            sendMessage("已有连接接入,请重试 ！");
            //关闭连接
            onClose();
        }
        sendMessage("当前连接状态: [ " + connected + " ]");
    }

    // 接收到客户端消息
    @OnMessage
    public void onMessage(String message) {
        log.info("客户端发来信息... {}", message);
    }

    // 服务器主动向客户端发送信息
    public void sendMessage(String message) {
        try {
            this.session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            log.error("发送消息异常：" + e.getMessage() + " --- 异常位置：" + e.getStackTrace());
        }
    }

    // 连接出错
    @OnError
    public void onError(Throwable error) {
        log.error("连接出错：{} , 错误信息： {}", error.getCause(), error.getMessage());
    }

    // 关闭连接
    @OnClose
    public void onClose() {
        this.session = null;
        this.sid = "";
        log.info("连接关闭...");
    }
}









